<?php
namespace App\Api\Controllers\Yinka;

use App\Api\Controllers\Config\VbillConfigController;
use App\Models\YinkaStore;
use Illuminate\Support\Facades\Log;
use App\Api\Controllers\Yinka\BaseController as base;
use function EasyWeChat\Kernel\Support\get_client_ip;

class PayController extends BaseController
{
    //扫一扫 0-系统错误 1-成功 2-正在支付 3-失败
    protected $_token;
    protected $_account;
    protected $_key;
    public function __construct($storeId)
    {
        $mch  = YinkaStore::where(['store_id' => $storeId])->first();
        $this->_token = $mch->token;
        $this->_account = $mch->account_id;
        $this->_key = $mch->pri_key;
    }


    public function scan_pay($data)
    {
        try {
            $params = [
                'authCode'    => $data['code'],
                'orgTrace' => $data['out_trade_no'],
                'tradeAmt'        => $data['total_amount'] * 100,
                'clientIp'    => get_client_ip(),
                'goodsDes' => '扫码收款'
            ];

            $base = base::getInstance();
            $ret  = $base->params($params, $this->_key)->build($base::SCAN_PAY, $this->_token);



            if (isset($ret['data']) && !empty($ret['data'])) {
                //1：待支付
                //2：已支付
                //3：支付失败
                //4：支付中
                //5：已关闭
                //6：已撤销
                //7：已退款
                //【注意】支付结果 除 2 和 3 外其余均需要轮询查询，直到有明确结果 成功或者失败
                if ($ret['data']['status'] == 2) { //支付成功
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret['data']
                    ];
                }
                if ($ret['data']['status'] == 3) { //支付失败
                    return [
                        'status' => 3,
                        'message' => $ret['data']['statusStr'],
                    ];
                }
                return [
                    'status' => 2,
                    'message' => '支付中',
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => '支付异常',
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 3,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //查询订单 0-系统错误 1-成功 2-正在支付 3-失败 4.已经退款

    public function order_query($data)
    {
        try {
            $params = [
                'orgTrace' => $data['out_trade_no']
            ];
            $base = base::getInstance();
            $ret  = $base->params($params, $this->_key)->build($base::ORDER_QUERY, $this->_token);
            error_log(date('Y-m-d H:i:s')." 【银卡被扫查询】： ".json_encode([$params, $ret])."\n\n", 3, "/tmp/". 'yinka'.date('Ymd').".log");


            if (isset($ret['data']) && !empty($ret['data'])) {
                //1：待支付
                //2：已支付
                //3：支付失败
                //4：支付中
                //5：已关闭
                //6：已撤销
                //7：已退款
                //【注意】支付结果 除 2 和 3 外其余均需要轮询查询，直到有明确结果 成功或者失败
                if ($ret['data']['status'] == 2) { //支付成功
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret['data']
                    ];
                }
                if ($ret['data']['status'] == 3) { //支付失败
                    return [
                        'status' => 3,
                        'message' => $ret['data']['statusStr'],
                    ];
                }
                return [
                    'status' => 2,
                    'message' => '支付中',
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => '支付异常',
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //退款 0-系统错误 1-成功
    public function refund($data)
    {
        try {
            $params = [
                'orgTrace' => $data['out_trade_no'],
                'transAmt' => $data['refund_fee'] * 100,
                'reason' => '退款'
            ];
            $base = base::getInstance();
            $ret  = $base->params($params, $this->_key)->build($base::REFUND, $this->_token);
            error_log(date('Y-m-d H:i:s')." 【银卡被扫退款】： ".json_encode([$params, $ret])."\n\n", 3, "/tmp/". 'yinka'.date('Ymd').".log");
            if (isset($ret['data']) && !empty($ret['data'])) {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => [
                        'refund_count' => 1,
                        'out_trade_no'  => $data['out_trade_no'],
                    ]
                ];
            } else {
                return [
                    'status' => 2,
                    'message' => isset($ret['msg']) ? $ret['msg'] : ''
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款查询 0-系统错误 1-成功 2-正在退款 3-失败
    public function refund_query($data)
    {
        try {


        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    public function qr_pay ($data)
    {
        try {
            $params = [
                'out_order_no' => $data['out_trade_no'],
                'client_ip' => get_client_ip(),
                'money' => $data['total_amount'] * 100,
                'notify_url' => $data['notify_url']
            ];
            $base = base::getInstance();
            
            $ret  = $base->params($params, $this->_key)->build($base::JS_API_PAY, $this->_token);
            
            // $ret  = $base->params($params, $this->_key, $this->_account)->build($base::JS_API_PAY, $this->_token);
            Log::channel('daily')->debug(sprintf("== 银卡主扫 请求 ==\n【api】%s\n【入参】%s\n【响应】%s\n", $base::REFUND, json_encode($params), json_encode($ret)));
            error_log(date('Y-m-d H:i:s')." 【银卡主扫】： ".json_encode([$params, $ret])."\n\n", 3, "/tmp/". 'yinka'.date('Ymd').".log");

            if (isset($ret['data']['response']) && !empty($ret['data']['response'])) {
                return [
                    'status' => 1,
                    'message' => '成功',
                    'data' => [
                        'codeUrl'  => $ret['data']['response']['web_url'],
                    ]
                ];
            } else {
                return [
                    'status' => 2,
                    'message' => $ret['msg']
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }





}
